﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCoreStudy.Web.Models;
using DotNetCoreStudy.Web.services;
using Microsoft.AspNetCore.Mvc;

namespace DotNetCoreStudy.Web.Controllers
{
    public class EmployeeController : Controller
    {
        private readonly IDepartmentService _departmentService;
        private readonly IEmployeeService _employeeService;

        public EmployeeController(IDepartmentService departmentService, IEmployeeService employeeService)
        {
            _departmentService = departmentService;
            _employeeService = employeeService;
        }

        /// <summary>
        /// 获取指定部门下所有员工的信息
        /// </summary>
        /// <param name="departmentId"></param>
        /// <returns></returns>
        public async Task<IActionResult> Index(int departmentId)
        {
            var department = await _departmentService.GetDepartmentById(departmentId);
            ViewBag.Title = $"Employees of {department.Name}";
            ViewBag.DepartmentId = departmentId;
            var employees = await _employeeService.GetEmployeeByDepartmentId(departmentId);
            return View(employees);
        }

        public IActionResult Add(int departmentId)
        {
            ViewBag.Tile = "Add Employee";
            ViewBag.DepartmentId = departmentId;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Add(Employee model)
        {
            if (ModelState.IsValid) //验证model传参是否合法
            {
                await _employeeService.Add(model);
            }
            return RedirectToAction(nameof(Index), routeValues: new { departmentId = model.DepartmentId });
        }

        public async Task<IActionResult> Edit(int employeeId)
        {
            ViewBag.Tile = "Edit Employee";
            var employee = await _employeeService.GetEmployeeById(employeeId);
            ViewBag.EmployeeId = employeeId;
            return View(employee);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(Employee model)
        {
            if (ModelState.IsValid) //验证model传参是否合法
            {
                await _employeeService.Update(model);
            }
            return RedirectToAction(nameof(Index), routeValues: new { departmentId = model.DepartmentId });
        }


        /// <summary>
        /// 根据员工id解雇员工
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        public async Task<IActionResult> Fire(int employeeId)
        {
            var employee = await _employeeService.Fire(employeeId);
            return RedirectToAction(nameof(Index), routeValues: new { departmentId = employee.DepartmentId });
        }
    }
}